<script lang="ts">
export default {
  name: 'tenantList'
};
</script>

<script setup lang="ts">
import { getAllGmtTimeList } from '@/utils/utils';
import { statusOptionList } from '@/option'
import { listTenant, addTenant, updateTenant, deleteListTenant, updateTenantMenus, tenantPermissionList } from '@/api/tenant';

import { TenantForm, TenantQuery, TenantPageVO } from '@/api/tenant/types';

import { tree } from '@/utils/utils'

const queryFormRef = ref(ElForm);
const tenantFormRef = ref(ElForm);
const menuRef = ref(ElTree);

const defaultTime: [Date, Date] = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
];
const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);
const defaultProps = reactive({
  children: 'children',
  label: 'label'
})


const queryParams = reactive<TenantQuery>({
  current: 1,
  pageSize: 10,
  tenantName: '',
  status: undefined,
  beginTime: '',
  endTime: ''
});

const roleList = ref<TenantQuery[]>();

const dialog = reactive<DialogOption>({
  visible: false
});

const formData = reactive<TenantForm>({
  tenantName: '',
  status: 1,
  beginTime: '',
  endTime: '',
  beginEndTime: ''
});

const menuDialogVisible = ref(false);
const menuList = ref<OptionType[]>([]);

interface allDataListType extends TenantPageVO {
  permission?: number;
  action?: string;
  method?: string;
}
const allDataList = ref<allDataListType[]>([]);
const defaultCheckedKeys = ref<number[]>([]);
interface CheckedRole {
  id?: number;
  name?: string;
}
let checkedRole: CheckedRole = reactive({});

const rules = reactive({
  tenantName: [{ required: true, message: '请输入租户名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  beginEndTime: [{ required: true, message: '请选择有效时间', trigger: 'blur' }]
});


/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  listTenant(queryParams)
    .then((res) => {
      roleList.value = getAllGmtTimeList(res.data?.data);

      total.value = res.data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
/**
 * 重置查询
 */
function resetQuery() {
  // queryFormRef.value.resetFields();
  queryParams.current = 1;
  handleQuery();
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开租户表单弹窗
 *
 * @param row //行对象
 */
function openDialog(row?: TenantPageVO) {
  dialog.visible = true;
  if (row && row.id) {
    dialog.title = '修改租户';
    Object.assign(formData, row);
  } else {
    dialog.title = '新增租户';
  }
}

/**
 * 租户表单提交
 */
function handleSubmit() {
  loading.value = true;
  tenantFormRef.value.validate((valid: any) => {
    if (valid) {
      if (formData.id) {
        updateTenant(formData)
          .then(() => {
            ElMessage.success('修改成功');
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addTenant(formData)
          .then(() => {
            ElMessage.success('新增成功');
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  tenantFormRef.value.resetFields();
  tenantFormRef.value.clearValidate();

  formData.id = undefined;
  formData.tenantName = '';
  // formData.beginTime = '';
  // formData.endTime = '';
  formData.beginEndTime = '';
  formData.status = 1;
}

/**
 * 删除
 */
function handleDelete(id?: number) {
  let idList = ids.value
  id ? idList = [...ids.value, id] : null
  if (idList.length === 0) {
    ElMessage.warning('请勾选删除项');
    return;
  }
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteListTenant(idList)
      .then(() => {
        ElMessage.success('删除成功');
        handleQuery();
      })
  });
}

/**
 * 打开分配菜单弹窗
 */
function openMenuDialog(row: TenantPageVO) {
  const tenantId = row.id;
  if (tenantId) {
    checkedRole = {
      id: tenantId,
      name: row.tenantName
    };
    menuDialogVisible.value = true;
    loading.value = true;
    // 获取角色权限
    tenantPermissionList({ tenantId }).then((res: any) => {
      let { allData, userData } = res.data
      allDataList.value = allData
      menuList.value = tree(allData, 0, 'parentId')
      // 回显角色已拥有的菜单
      defaultCheckedKeys.value = userData || []
      menuRef.value.setCheckedKeys(defaultCheckedKeys.value)
      loading.value = false;
    });
  }
}

/**
 * 角色分配菜单提交
 */
function handleRoleMenuSubmit() {
  const tenantId = checkedRole.id;
  if (tenantId) {
    // .concat(menuRef.value.getHalfCheckedKeys())
    let menuIds = menuRef.value.getCheckedKeys()
    let filterData = allDataList.value.filter((ele: any) => menuIds.includes(ele.id))
    let menuIdList = filterData.map((ele) => {
      return {
        menuId: ele.id,
      }
    })

    loading.value = true;
    updateTenantMenus({
      menuIdList,
      tenantId
    })
      .then(res => {
        ElMessage.success('分配权限成功');
        menuDialogVisible.value = false;
        resetQuery();
      })
      .finally(() => {
        loading.value = false;
      });
  }
}


onMounted(() => {
  handleQuery();
});

watch(
  () => formData.beginEndTime,
  (val: any) => {
    formData.beginTime = val[0];
    formData.endTime = val[1];
  }
);
</script>

<template>
  <div class="app-container">
    <!-- <div class="search">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item prop="name" label="关键字">
              <el-input v-model="queryParams.name" placeholder="租户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <i-ep-search />搜索
              </el-button>
              <el-button @click="resetQuery">
                <i-ep-refresh />重置
              </el-button>
            </el-form-item>
          </el-form>
        </div> -->

    <el-card shadow="never">
      <template #header>
        <!-- <el-button type="success" @click="openDialog()">
          <i-ep-plus />新增
        </el-button>
        <el-button type="danger" :disabled="ids.length === 0" @click="handleDelete()">
          <i-ep-delete />删除
        </el-button> -->
      </template>

      <el-table ref="dataTableRef" v-loading="loading" :data="roleList" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="租户名称" prop="tenantName" align="center" width="300" />
        <el-table-column label="有效时间" align="center">
          <template #default="scope">
            {{ scope.row.beginTime }} - {{ scope.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createBy" width="160" align="center" />
        <el-table-column label="创建时间" prop="createTime" align="center" />
        <el-table-column label="更新人" prop="lastUpdateBy" width="160" align="center" />
        <el-table-column label="更新时间" prop="lastUpdateTime" align="center" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" link @click="openMenuDialog(scope.row)">
              <i-ep-position />分配权限
            </el-button>
            <el-button type="primary" size="small" link @click="openDialog(scope.row)">
              <i-ep-edit />编辑
            </el-button>
            <el-button type="primary" size="small" link @click="handleDelete(scope.row.id)">
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.current"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
    </el-card>

    <!-- 租户表单弹窗 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" @close="closeDialog">
      <el-form ref="tenantFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="租户名称" prop="tenantName">
          <el-input v-model="formData.tenantName" placeholder="请输入租户名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <template v-for="item in statusOptionList" :key="item.value">
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </template>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item prop="beginEndTime" label="有效时间">
          <el-date-picker v-model="formData.beginEndTime" type="datetimerange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime">
          </el-date-picker>
        </el-form-item> -->
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分配菜单弹窗  -->
    <el-dialog :title="'【' + checkedRole.name + '】权限分配'" v-model="menuDialogVisible" width="800px">
      <el-scrollbar max-height="600px" v-loading="loading">
        <el-tree ref="menuRef" node-key="id" show-checkbox :data="menuList" :default-expand-all="true" highlight-current
          check-on-click-node :default-checked-keys="defaultCheckedKeys" :props="defaultProps">
          <template #default="{ data }">
            {{ data.label }}
          </template>
        </el-tree>
      </el-scrollbar>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleRoleMenuSubmit">确 定</el-button>
          <el-button @click="menuDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
